package com.flea.web.websocket;

import com.flea.util.SessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.websocket.WsSession;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
@Component
@ServerEndpoint("/message")
public class MessageCountWebSocketHandler {

    //<sessionId,Session>
    private static List<WsSession> sessionList = new CopyOnWriteArrayList<>();

    @OnOpen
    public void onOpen(Session session) {
        log.info("{} 请求连接", session.getId());
        sessionList.add((WsSession) session);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("有一连接关闭 {}", session.getId());
        sessionList.remove(session);
    }


    /**
     * 接收消息
     *
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到页面上的消息：{}", message);

    }

    public void sendMessage(Integer userId, String message) {
        // 根据userId查找websocket session
        List<String> httpSessionList = SessionUtils.getHttpSessionId(userId);
        if (httpSessionList.isEmpty()) {
            return;
        }

        sessionList.stream().filter(e -> httpSessionList.contains(e.getHttpSessionId())).forEach(e -> {
            try {
                e.getBasicRemote().sendText(message);
            } catch (IOException ioe) {
                log.warn("Send web socket message fail", ioe);
            }
        });
    }

    public void sendMessage(Integer messageCount) {
        sessionList.forEach(session -> {
            try {
                session.getBasicRemote().sendText(String.valueOf(messageCount));
            } catch (IOException e) {
                log.warn("Send web socket message fail", e);
            }
        });
    }

}
